<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>43.使用await封装Ajax</title>
</head>
<body>
<script>

    //定义一个函数发送Ajax，返回是promise对象
    function sendAjax(url) {
       let result = new Promise((resolve, reject) => {
            var xhr = new XMLHttpRequest()
            xhr.open('get',url)
            xhr.send()
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4){
                    //对于状态码正常的使用resolve
                    if (xhr.status >= 200 && xhr.status < 300){
                        resolve(xhr.response)
                    }else {
                        //状态码异常的使用reject
                        reject(xhr.status)
                    }
                }
            }
        })

        return result
    }

    //使用async定义一个函数
    async function  m1(){
        try{
            //使用await接受一下promise对象resolve返回的值
            let result = await sendAjax('http://127.0.0.1:8000/server')
            console.log(result)  
        }catch (e) {
            //使用异常捕获获得reject的值
            console.log(e)
        }
 
    }
    
    m1()
    

</script>
</body>
</html>